package com.bhs.sansonglogistics.ui.enterprise;

import static com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity.RC_LOCATION;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.CompanyInfoBean;
import com.bhs.sansonglogistics.bean.SlideshowBean;
import com.bhs.sansonglogistics.bean.event.CompanyInfo;
import com.bhs.sansonglogistics.dialog.BottomAffiliationDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.net.Config;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.other.WebViewActivity;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.banner.AutoScrollViewPager;
import com.bhs.sansonglogistics.view.banner.ViewPagerAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

/**
 * 企业入驻
 */
public class EnterpriseSettlementActivity extends BaseActivity implements View.OnClickListener, TextWatcher, NetCallBack, EasyPermissions.PermissionCallbacks {


    private TextView mTvTitle;
    private LinearLayout mLlBusinessLicense;
    private EditText mEtCompanyName;
    private Switch mSwInvoice;
    private CheckBox mCbElectronicInvoice;
    private CheckBox mCbPaperInvoice;
    private EditText mEtTaxRate;
    private EditText mEtAnnouncement;
    private EditText mEtPrincipal;
    private EditText mEtPhone;
    private EditText mLandlineNumber;
    private EditText mEtQueryPhone;
    private TextView mEtCompanyAddress;
    private TextView mTvSuoshuyuanqu;
    private TextView mTvBusinessLicense;
    private TextView mTvTransportPolicy;
    private CheckBox mCbAgreement;
    private Button mBtnSubmit;
    private FrameLayout mFlLocation;
    private TextView mTvAnnouncementWordCount;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private double latitude, longitude;
    private String province;
    private String city;
    private String county;
    private BottomAffiliationDialog affiliationDialog;
    private List<SlideshowBean> bannerList = new ArrayList<>();
    private AutoScrollViewPager mVpCarousel;
    private TextView mTvIndexes;
    private LinearLayout mLlInvoiceForm;
    private TextView mTvInvoiceForm;

    private CompanyInfoBean infoBean;
    private LinearLayout mLlCompanyName;
    private TextView mTvCompanyName;
    private LinearLayout mLlTaxRate;

    @Override
    public int initLayout() {
        return R.layout.activity_enterprise_settlement;
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    public void initView() {

        mTvTitle = findViewById(R.id.tv_title);
        mLlBusinessLicense = findViewById(R.id.ll_business_license);
        mLlBusinessLicense.setOnClickListener(this);
        mEtCompanyName = findViewById(R.id.et_company_name);
        mSwInvoice = findViewById(R.id.sw_invoice);
        mCbElectronicInvoice = findViewById(R.id.cb_electronic_invoice);
        mCbPaperInvoice = findViewById(R.id.cb_paper_invoice);
        mEtTaxRate = findViewById(R.id.et_tax_rate);
        mEtAnnouncement = findViewById(R.id.et_announcement);
        mEtPrincipal = findViewById(R.id.et_principal);
        mEtPhone = findViewById(R.id.et_phone);
        mLandlineNumber = findViewById(R.id.landline_number);
        mEtQueryPhone = findViewById(R.id.et_query_phone);
        mEtCompanyAddress = findViewById(R.id.et_company_address);
        mTvSuoshuyuanqu = findViewById(R.id.tv_suoshuyuanqu);
        mTvBusinessLicense = findViewById(R.id.tv_business_license);
        mTvTransportPolicy = findViewById(R.id.tv_transport_policy);
        mCbAgreement = findViewById(R.id.cb_agreement);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mFlLocation = findViewById(R.id.fl_location);
        mEtQueryPhone.addTextChangedListener(this);
        mFlLocation.setOnClickListener(this);
        mTvBusinessLicense.setOnClickListener(this);
        mTvTransportPolicy.setOnClickListener(this);
        mTvAnnouncementWordCount = findViewById(R.id.tv_announcement_word_count);
        mEtTaxRate.addTextChangedListener(this);
        mEtPhone.addTextChangedListener(this);
        mLandlineNumber.addTextChangedListener(this);
        mEtPrincipal.addTextChangedListener(this);
        mTvSuoshuyuanqu.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);
        findViewById(R.id.rl_carousel).setOnClickListener(this);
        mCbAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                verify();
            }
        });
        mVpCarousel = findViewById(R.id.vp_carousel);
        mTvIndexes = findViewById(R.id.tv_indexes);
        mLlInvoiceForm = findViewById(R.id.ll_invoice_form);
        mTvInvoiceForm = findViewById(R.id.tv_invoice_form);
        mLlCompanyName = findViewById(R.id.ll_company_name);
        mTvCompanyName = findViewById(R.id.tv_company_name);
        mLlTaxRate = findViewById(R.id.ll_tax_rate);

        String str = "我已阅读并同意《企业入驻协议》";

        SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(str);
        // 在设置点击事件、同时设置字体颜色
        ClickableSpan clickableSpanOne = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, WebViewActivity.class)
                        .putExtra("url", Config.getEnterUrl())
                        .putExtra("title", "企业入驻协议"));
            }

            @Override
            public void updateDrawState(TextPaint paint) {
                paint.setColor(Color.parseColor("#485EF4"));
                // 设置下划线 true显示、false不显示
                paint.setUnderlineText(false);
            }
        };
        spannableBuilder.setSpan(clickableSpanOne, 7, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mCbAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        mCbAgreement.setText(spannableBuilder);

        mEtPrincipal.setFilters(new InputFilter[]{filter});
        mEtAnnouncement.setFilters(MyUtils.inputFilters(mActivity, 300));


    }

    @Override
    public void initData() {
        mTvTitle.setText("企业入驻");
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                LogUtils.d("" + result.getResultCode());
                //此处是跳转的result回调方法
                if (result.getResultCode() == 3) {
                    if (result.getData() != null) {
                        mEtCompanyAddress.setText(result.getData().getStringExtra("address"));
                        longitude = result.getData().getDoubleExtra("longitude", 0);
                        latitude = result.getData().getDoubleExtra("latitude", 0);
                        city = result.getData().getStringExtra("city");
                        province = result.getData().getStringExtra("province");
                        county = result.getData().getStringExtra("county");
                        mTvSuoshuyuanqu.setText("");
                        mTvSuoshuyuanqu.setTag("");
                    }
                    verify();
                } else {
                    networkRequest(netApi.getCompanyInfo(), EnterpriseSettlementActivity.this);
                }
            }
        });


        mEtAnnouncement.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 300) {
                    mEtAnnouncement.setText(s.subSequence(0, 300));
                    Selection.setSelection(mEtAnnouncement.getText(), 300);
                }
                mTvAnnouncementWordCount.setText(String.format("%s/300", s.length()));
                verify();
            }
        });
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mSwInvoice.getLayoutParams());
        mSwInvoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                mLlInvoiceForm.setVisibility(b ? View.VISIBLE : View.GONE);
                mLlTaxRate.setVisibility(b ? View.VISIBLE : View.GONE);
                if (b) {
                    lp.setMargins(0, 0, 0, 0);
                    mSwInvoice.setLayoutParams(lp);
                } else {
                    lp.setMargins(0, 0, 0, 40);
                    mSwInvoice.setLayoutParams(lp);
                }
            }
        });
        networkRequest(netApi.getCompanyInfo(), this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVpCarousel.startAutoPlay();
    }


    @Override
    public void onStop() {
        super.onStop();
        if (mVpCarousel != null) {
            mVpCarousel.stopAutoPlay();
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_carousel:
            case R.id.ll_business_license:
                Intent intent = new Intent(EnterpriseSettlementActivity.this, CompanyPhotoUploadingActivity.class);
                intentActivityResultLauncher.launch(intent);
                break;
            case R.id.tv_suoshuyuanqu:
                affiliationDialog = new BottomAffiliationDialog(mActivity, city);
                affiliationDialog.setMyClickListener(new MyClickListener2() {
                    @Override
                    public void onClick(String id, String info) {
                        mTvSuoshuyuanqu.setText(info);
                        mTvSuoshuyuanqu.setTag(id);
                        verify();
                    }
                });
                affiliationDialog.show();
                break;
            case R.id.btn_submit:
                submit();
                break;
            case R.id.fl_location:
                methodRequiresTwoPermission();
                break;
            case R.id.tv_business_license:
                startActivity(new Intent(mActivity, CheckAttachmentActivity.class)
                        .putExtra("attachment", infoBean.getData().getCompany_imgs().getLicense_pic().get(0))
                        .putExtra("title", "营业执照"));
                break;
            case R.id.tv_transport_policy:
                Intent intent1 = new Intent(mActivity, TransportPolicyActivity.class)
                        .putStringArrayListExtra("attachment", infoBean.getData().getCompany_imgs().getInsurance_pics());
                intentActivityResultLauncher.launch(intent1);
                break;
        }
    }

    String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE};

    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            goPage();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "我需要您的位置信息",
                    RC_LOCATION, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {

        }

    }

    public void goPage() {
        Intent intent = new Intent(this, LocationSelectionActivity.class);
        intentActivityResultLauncher.launch(intent);
    }

    //当申请的权限里有一个或多个被允许时
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (RC_LOCATION == requestCode) {
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    private void submit() {
        if (mSwInvoice.isChecked() && (!mCbElectronicInvoice.isChecked() && !mCbPaperInvoice.isChecked())) {
            ToastUtil.show("请选择发票形式");
            return;
        }
        if (mSwInvoice.isChecked() && Double.parseDouble(mEtTaxRate.getText().toString()) <= 0) {
            ToastUtil.show("税点需要大于0");
            return;
        }
        if (!MyUtils.isPhone(mEtPhone.getText().toString())) {
            ToastUtil.show("请输入正确的手机号码");
            return;
        }
        loadingPopupShow();
        Map<String, String> map = new ArrayMap<>();
        map.put("company_name", mEtCompanyName.getText().toString());
        map.put("contact", mEtPrincipal.getText().toString());
        map.put("mobile", mEtPhone.getText().toString());
        map.put("province", province);
        map.put("city", city);
        map.put("county", county);
        map.put("address", mEtCompanyAddress.getText().toString());
        map.put("latitude", String.valueOf(latitude));
        map.put("longitude", String.valueOf(longitude));
        map.put("is_fapiao", mSwInvoice.isChecked() ? "1" : "0");
        map.put("fapiao_electron_status", mCbElectronicInvoice.isChecked() ? "1" : "0");
        map.put("fapiao_paper_status", mCbPaperInvoice.isChecked() ? "1" : "0");
        map.put("fapiao_tax_point", mEtTaxRate.getText().toString());
        map.put("public_notice", mEtAnnouncement.getText().toString());
        map.put("fixed_telephone", mLandlineNumber.getText().toString());
        map.put("search_phone", mEtQueryPhone.getText().toString());
        map.put("park_id", (String) mTvSuoshuyuanqu.getTag());
        networkRequest(netApi.companySettled(map), this, 9527);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    private void verify() {
        boolean verify = true;
        if (TextUtils.isEmpty(mEtCompanyName.getText()) || TextUtils.isEmpty(mEtTaxRate.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtPrincipal.getText()) || TextUtils.isEmpty(mEtPhone.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtCompanyAddress.getText()) || TextUtils.isEmpty(mTvSuoshuyuanqu.getText())) {
            verify = false;
        }
        if (!mCbAgreement.isChecked() || TextUtils.isEmpty(mLandlineNumber.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtQueryPhone.getText())) {
            verify = false;
        }
        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            infoBean = new Gson().fromJson(json, CompanyInfoBean.class);
            if (infoBean.isStatus()) {
                bannerList.clear();
                CompanyInfo data = infoBean.getData().getCompany_info();
                for (String s : infoBean.getData().getCompany_imgs_all()) {
                    bannerList.add(new SlideshowBean(s));
                }
                if (bannerList.size() > 0) {
                    mLlBusinessLicense.setVisibility(View.GONE);
                    mTvIndexes.setVisibility(View.VISIBLE);
                    mTvIndexes.setText(String.format("%s/%s", 1, bannerList.size()));
                    ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(bannerList, this, true, false);
                    mVpCarousel.setAdapter(pagerAdapter);
                    mVpCarousel.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                            mTvIndexes.setText(String.format("%s/%s", position % bannerList.size() + 1, bannerList.size()));
                        }
                    });
                    pagerAdapter.setIOnItemClick(new ViewPagerAdapter.IOnItemClick() {
                        @Override
                        public void onItemClick(int position) {
                            Intent intent = new Intent(EnterpriseSettlementActivity.this, CompanyPhotoUploadingActivity.class);
                            intentActivityResultLauncher.launch(intent);
                        }
                    });
                } else {
                    mLlBusinessLicense.setVisibility(View.VISIBLE);
                }

                if (TextUtils.isEmpty(mEtPrincipal.getText())) {
                    if (data.getFapiao_tax_point().equals("0.00")) {
                        mEtTaxRate.setText("0");
                    } else {
                        mEtTaxRate.setText(data.getFapiao_tax_point());
                    }
                    if (!MyUtils.isEmpty(infoBean.getData().getCompany_imgs().getInsurance_pics())) {
                        mTvTransportPolicy.setText("点击查看");
                    }

                    if (data.getIs_company_approve() == 1) {
                        mLlCompanyName.setVisibility(View.VISIBLE);
                        mEtCompanyName.setVisibility(View.GONE);
                    } else {
                        mLlCompanyName.setVisibility(View.GONE);
                        mEtCompanyName.setVisibility(View.VISIBLE);
                    }
                    mTvCompanyName.setText(data.getCompany_name());
                    mEtCompanyName.setText(data.getCompany_name());
                    mEtPrincipal.setText(data.getContact());
                    mEtPhone.setText(data.getMobile());
                    mEtCompanyAddress.setText(data.getAddress());
                    province = data.getProvince();
                    city = data.getCity();
                    county = data.getCounty();
                    longitude = Double.parseDouble(data.getLongitude());
                    latitude = Double.parseDouble(data.getLatitude());
                    mSwInvoice.setChecked(data.getIs_fapiao() != 0);
                    mCbPaperInvoice.setChecked(data.getFapiao_paper_status() == 1);
                    mCbElectronicInvoice.setChecked(data.getFapiao_electron_status() == 1);

                    mEtAnnouncement.setText(data.getPublic_notice());
                    mLandlineNumber.setText(data.getFixed_telephone());
                    mEtQueryPhone.setText(data.getSearch_phone());
                    mTvSuoshuyuanqu.setText(data.getPark_name());
                    mTvSuoshuyuanqu.setTag(String.valueOf(data.getPark_id()));

                }

            }
        } else {
            loadingPopupDismiss();
            BaseBean dataBean = new Gson().fromJson(json, BaseBean.class);
            new XPopup.Builder(this)
                    .asConfirm("提示", dataBean.getMsg(),
                            null, "确定",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    if (dataBean.isStatus()) {
                                        finish();
                                    }
                                }
                            }, null, true)
                    .show();
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                if (!isChinese(source.charAt(i))) {
                    return "";
                }
            }
            return null;
        }

        private boolean isChinese(char c) {
            return c >= 0x4E00 && c <= 0x9FA5;
        }
    };

}